#include "stm32f10x.h"                  // Device header
#include <stdio.h>
#include <stdarg.h>
#include "delay.h"	
#include "Serial.h"
#include "OLED.h"

unsigned int USART3_RxCounter = 0;      //定义一个变量，记录串口2总共接收了多少字节的数据
char USART3_RxBuff[USART3_RXBUFF_SIZE]; //定义一个数组，用于保存串口2接收到的数据   	

volatile uint16_t USART3_RX_STA = 0;


/*-------------------------------------------------*/
/*函数名：初始化串口3发送功能                      */
/*参  数：bound：波特率                            */
/*返回值：无                                       */
/*-------------------------------------------------*/
void USART3_init(unsigned int bound)
{  	 	
    GPIO_InitTypeDef GPIO_InitStructure;     //定义一个设置GPIO功能的变量
	USART_InitTypeDef USART_InitStructure;   //定义一个设置串口功能的变量
	NVIC_InitTypeDef NVIC_InitStructure;     //如果使能接收功能，定义一个设置中断的变量
      	
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE); //使能串口2时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);  //使能GPIOA时钟
	USART_DeInit(USART3);                                  //串口2寄存器重新设置为默认值
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;              //准备设置PA2
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;      //IO速率50M
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	       //复用推挽输出，用于串口2的发送
    GPIO_Init(GPIOB, &GPIO_InitStructure);                 //设置PA2
   
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;              //准备设置PA3
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;  //浮空输入，用于串口2的接收
    GPIO_Init(GPIOB, &GPIO_InitStructure);                 //设置PA3
	
	USART_InitStructure.USART_BaudRate = bound;                                    //波特率设置
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;                    //8个数据位
	USART_InitStructure.USART_StopBits = USART_StopBits_1;                         //1个停止位
	USART_InitStructure.USART_Parity = USART_Parity_No;                            //无奇偶校验位
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
	USART_InitStructure.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;	               //收发模式
      
    USART_Init(USART3, &USART_InitStructure);                                      //设置串口2	

	USART_ClearFlag(USART3, USART_FLAG_RXNE);	              //清除接收标志位
	USART_ITConfig(USART3, USART_IT_RXNE, ENABLE);            //开启接收中断
	USART_ITConfig(USART3, USART_IT_IDLE, ENABLE);            // 开启空闲中断
    NVIC_InitStructure.NVIC_IRQChannel = USART3_IRQn;         //设置串口2中断
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //抢占优先级
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;		  //子优先级0
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			  //中断通道使能
	NVIC_Init(&NVIC_InitStructure);	                          //设置串口2中断 

	USART_Cmd(USART3, ENABLE);                                //使能串口2
}

/*-------------------------------------------------*/
/*函数名：串口2 printf函数                         */
/*参  数：char* fmt,...  格式化输出字符串和参数    */
/*返回值：无                                       */
/*-------------------------------------------------*/

__align(8) char USART3_TxBuff[USART3_TXBUFF_SIZE];  

void u2_printf(char* fmt, ...) 
{  
	unsigned int i, length;
	
	va_list ap;
	va_start(ap, fmt);
	vsprintf(USART3_TxBuff, fmt, ap);
	va_end(ap);	
	
	length=strlen((const char*)USART3_TxBuff);		
	while((USART3->SR&0X40) == 0);
	for(i = 0; i < length; i++)
	{			
		//USART_SendData(USART3,USART3_TxBuff[i]);
		USART3->DR = USART3_TxBuff[i];
		while((USART3->SR&0X40) == 0);	
	}	
}

/*-------------------------------------------------*/
/*函数名：串口2发送缓冲区中的数据                  */
/*参  数：data：数据                               */
/*返回值：无                                       */
/*-------------------------------------------------*/
void u2_TxData(unsigned char *data)
{
	int	i;	
	while((USART3->SR&0X40) == 0);
	for(i = 1; i <= (data[0] * 256 + data[1]); i++)
	{			
		USART3->DR = data[i+1];
		while((USART3->SR&0X40) == 0);	
	}
}
/*-------------------------------------------------*/
/*函数名：串口2接收缓冲区中的数据                  */
/*参  数：无                                       */
/*返回值：返回接收到数据                           */
/*-------------------------------------------------*/
char *USART3_Rxbuff(void)
{
	if(USART3_RX_STA == 1)
	{
		USART3_RxBuff[USART3_RxCounter] = '\0';
		return USART3_RxBuff;
	}
	else
    {
        return NULL;
    }
}
char WiFi_SendCmd(char *cmd, char *ack ,int timeout)
{
	char *ret = NULL;
	USART3_RX_STA = 0;
	USART3_RxCounter = 0;
	memset(USART3_RxBuff,0,USART3_RXBUFF_SIZE);
	esp8266_printf("%s\r\n", cmd);
	if ((ack == NULL) || (timeout == 0))
    {
        return ATK_MW8266D_EOK;
    }
	while(timeout--)
	{
		ret = USART3_Rxbuff();
		if (ret != NULL)
		{
			if (strstr((const char *)ret, ack) != NULL)
			{
				return ATK_MW8266D_EOK;//代表正常
			}
			else
			{
				USART3_RX_STA = 0;
				USART3_RxCounter = 0;
			}
		}
		Delay_ms(1);
	}
	return ATK_MW8266D_ETIMEOUT;
}
void WiFi_GPIOInit(void)
{
	GPIO_InitTypeDef GPIO_InitStructure;
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStructure);

}
uint8_t WiFi_reset(uint16_t time)
{
	char *ret = NULL;
	GPIO_ResetBits(GPIOA,GPIO_Pin_8);
	Delay_ms(100);
	GPIO_SetBits(GPIOA,GPIO_Pin_8);
	Delay_ms(500);
	while(time--)
	{
		ret = USART3_Rxbuff();
		if (ret != NULL)
		{
			if (strstr((const char *)ret, "ok") != NULL)
			{
				return ATK_MW8266D_EOK;//代表正常
			}
			else
			{
				USART3_RX_STA = 0;
				USART3_RxCounter = 0;
			}
		}
		Delay_ms(1);
	}
	return ATK_MW8266D_ERROR;
}

uint8_t WiFi_Iot_server(void)
{
	printf("准备复位模块\r\n");
	if(WiFi_reset(500))
	{
		printf("复位失败\r\n");
		return 1;
	}else
	printf("复位成功\r\n");
	return 0;
}
uint8_t WiFi_Iot_touchuan(void)
{
	volatile uint16_t number = 0;
  esp8266_printf("+++");
	Delay_ms(1000);
	WiFi_SendCmd("AT+RST", "OK", 3000);
	Delay_ms(1000);
	WiFi_SendCmd("AT+CWMODE=1", "OK", 5000);

	WiFi_SendCmd("AT+CWJAP=\"WiFi123\",\"123456789\"", "WIFI GOT IP", 5000);
  Delay_ms(3000);
	
	WiFi_SendCmd("AT+CIPSTART=\"TCP\",\"112.74.142.132\",8647","OK",5000);
	Delay_ms(3000);
	
	WiFi_SendCmd("AT+CIPMODE=1", "OK", 1000);
	
	WiFi_SendCmd("AT+CIPSEND", "OK", 1000);
	
	esp8266_printf("79172HL5PTCNFYKT");

}

